<template>
  <el-upload
    ref="upload"
    :file-list="uploadedFiles"
    :headers="headers"
    :action="action"
    :multiple="multiple"
    :data="data"
    :limit="limit"
    :name="name"
    :accept="accept"
    :on-success="onSuccess"
    :on-remove="onRemove"
    :before-remove="beforeRemove"
    :on-exceed="onExceed"
    :on-error="onError"
    class="admin"
    list-type="picture-card"
  >
    <i class="el-icon-plus"/>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'AdminUpload',
  props: {
    multiple: {
      type: Boolean,
      default: true,
    },
    limit: {
      type: Number,
      default: 0,
    },
    name: String,
    value: {
      type: Array,
      default: () => [],
    },
    action: {
      type: String,
      default: '',
    },
    accept: String,
  },
  data() {
    return {
      headers: {
        Authorization: getToken(),
        'X-Requested-With': 'XMLHttpRequest',
      },
      data: {
        _upload_field: this.name,
      },
    }
  },
  computed: {
    uploadedFiles() {
      return this.value.filter(f => !f.removed)
    },
  },
  methods: {
    onSuccess(res) {
      this.value.push(res)
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除<br>${file.name}？`, {
        title: '移除确认',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      })
    },
    onRemove(file) {
      file.removed = true
    },
    onExceed() {
      this.$message({
        message: `最多只能上传${this.limit}个文件`,
        type: 'warning',
      })
    },
    onError(res) {
      if (res.status === 422) {
        const data = JSON.parse(res.message)
        const error = data.errors[this.name]
        const msg = error.join('<br>')
        this.$message.error({
          message: msg,
          dangerouslyUseHTMLString: true,
        })
      }
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss">
$size: 90px;
$circle-size: 85px;
.admin {
  .el-upload--picture-card,
  .el-upload-list--picture-card .el-upload-list__item {
    width: $size;
    height: $size;
  }

  .el-upload--picture-card {
    line-height: $size;
  }

  .el-upload-list--picture-card {
    .el-progress {
      width: $circle-size;

      .el-progress-circle {
        width: $circle-size !important;
        height: $circle-size !important;
      }
    }
  }
}
</style>
